{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Portmantout Words\n",
    "\n",
    "A *portmanteau* is a word that squishes together two overlapping words, like  *math* + *athlete* = *mathlete*. You can make up your own, like *eskimo* + *kimono* = *eskimono*. Inspired by Darius Bacon, I covered this as a programming exercise in my 2012 [Udacity course](https://www.udacity.com/course/design-of-computer-programs--cs212). Recently I was re-inspired by [Tom Murphy VII](http://www.cs.cmu.edu/~tom7), who added a new twist:  **[portmantout words](http://www.cs.cmu.edu/~tom7/portmantout/)**, which are defined as:\n",
    "\n",
    "> Given a set of words, W, a portmantout of W is a string, S, such that:\n",
    "* Each word in W is a substring of S.\n",
    "* S is formed by joining together an ordered list, L, of words from W (possibly with repeats).\n",
    "* For each word in L, some ending letter(s) must match the starting letters of the next word.\n",
    "* When L is joined into S, those overlapping letters appear only once.\n",
    "* The shorter the string S, the better.\n",
    "\n",
    "To make sure we understand the definition, I'll define the function `S = portman(L).` To find the overlap between two words, `portman` considers each suffix of the previous word and takes the longest suffix that starts the next word; we drop that from the word. (I'll also define functions to list the prefixes and suffixes of a word.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def portman(words):\n",
    "    \"Join a sequence of words, eliminating from each word the overlap with previous word.\"\n",
    "    prev = words[0]\n",
    "    result = [prev]\n",
    "    for word in words[1:]:\n",
    "        overlap = next(filter(word.startswith, suffixes(prev)))\n",
    "        result.append(word[len(overlap):])\n",
    "        prev = word\n",
    "    return ''.join(result)\n",
    "\n",
    "def prefixes(word) -> list:\n",
    "    \"All non-empty prefixes of word, shortest first.\"\n",
    "    return [word[:i+1] for i in range(len(word))]\n",
    "\n",
    "def suffixes(word) -> list:\n",
    "    \"All non-empty suffixes of word, longest first.\"\n",
    "    return [word[i:] for i in range(len(word))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# An example:\n",
    "W = {'on', 'one', 'two', 'won'}\n",
    "S = 'twone'\n",
    "L = ['two',\n",
    "      'won',\n",
    "       'on',\n",
    "       'one']\n",
    "\n",
    "assert portman(L) == S\n",
    "assert all(w in S for w in W)\n",
    "assert set(L) == W\n",
    "assert portman(['eskimo', 'kimono', 'monolith']) == 'eskimonolith'\n",
    "assert prefixes('word') == ['w', 'wo', 'wor', 'word']\n",
    "assert suffixes('word') == ['word', 'ord', 'rd', 'd']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that `portman(['one', 'two'])` would raise an error, because there is no overlap from `'one'` to `'two'`.\n",
    "\n",
    "# Problem-Solving Strategy\n",
    "\n",
    "I watched part of Tom Murphy's entertaining [video](https://www.youtube.com/watch?time_continue=1&v=QVn2PZGZxaI), but then I stopped because I wanted to solve the problem at least partially on my own. Here's my strategy:\n",
    "\n",
    "1. To start with, I'll need a list of words. Murphy provides [108,709 words](wordlist.asc) that I'll read that into a `Dictionary` data structure.\n",
    "2. This is clearly an NP-hard problem, so a greedy solution will suffice.\n",
    "3. In my [traveling salesperson notebook](TSP.ipynb) I show a greedy nearest neighbor solution: start at one city and continually go to the nearest unvisited city until all cities are visited. We can do a similar thing here: start at one word, and repeatedly go to the previously-unused word that maximizes overlap, until all words are used. \n",
    "4. However, this strategy has a problem: at some point it is likely that *none* of the remaining unused words overlap the current word. In that case, we'll need to re-use a word; I'll try to choose one that is short and that *bridges* to one of the remaining unused words.\n",
    "\n",
    "\n",
    "# Loading the Dictionary\n",
    "\n",
    "My `Dictionary` data structure contains three things:\n",
    "- A set of words.\n",
    "- A set of what I call *unique words*: the words that are not contained within other words. For example, \"on\" is contained within \"one\", so \"on\" would be in the set of words, but not the set of unique words.\n",
    "- Above I said I wanted to find \"previously-unused word that maximizes overlap.\" To facilitate that, I'll store a mapping from an overlap to a list of the words that have that overlap as a prefix, for example `{'o': ['on', 'one', ...], ...}`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict, Counter\n",
    "from functools import lru_cache\n",
    "\n",
    "class Dictionary:\n",
    "    \"A collection of words, with prefixes and unique words precomputed.\"\n",
    "    def __init__(self, stream):\n",
    "        self.words = {w.strip().lower() for w in stream}\n",
    "        self.uniq  = self.words - subwords(self.words)\n",
    "        self.pre   = multimap((p, w) for w in self.words for p in prefixes(w))\n",
    "        \n",
    "def subwords(words) -> set:\n",
    "    \"All words that are hiding inside any of these words.\"\n",
    "    return {sub for word in words\n",
    "                for i in range(len(word))\n",
    "                for sub in prefixes(word[i:])\n",
    "                if sub is not word and sub in words}\n",
    "\n",
    "def multimap(pairs) -> dict:\n",
    "    \"Given (key, val) pairs, make a dict of {key: [val,...]}.\"\n",
    "    result = defaultdict(list)\n",
    "    for key, val in pairs:\n",
    "        result[key].append(val)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'on', 'one', 'two', 'won'},\n",
       " {'one', 'two', 'won'},\n",
       " {'w': ['won'],\n",
       "  'wo': ['won'],\n",
       "  'won': ['won'],\n",
       "  'o': ['one', 'on'],\n",
       "  'on': ['one', 'on'],\n",
       "  'one': ['one'],\n",
       "  't': ['two'],\n",
       "  'tw': ['two'],\n",
       "  'two': ['two']})"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A small example:\n",
    "W = {'on', 'one', 'two', 'won'}\n",
    "d = Dictionary(W)\n",
    "d.words, d.uniq, dict(d.pre)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That looks right. Now I can load the big dictionary, call it `D`, and explore it a bit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "D = Dictionary(open('wordlist.asc'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(108709,\n",
       " 64389,\n",
       " 249623,\n",
       " ['somewhats',\n",
       "  'somewhen',\n",
       "  'somewise',\n",
       "  'someway',\n",
       "  'somewhere',\n",
       "  'someways',\n",
       "  'somewhat'])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(D.words), len(D.uniq), len(D.pre), D.pre['somew']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Finding Sequences of Overlapping Words\n",
    "\n",
    "The function `natalie` will take a Dictionary as input and produce a list of overlapping words, e.g.\n",
    "\n",
    "    d = Dictionary({'on', 'one', 'two', 'won'})\n",
    "    natalie(d) ⇒ ['two', 'won', 'on', 'one']\n",
    "    \n",
    "and we will solve the whole problem as follows:\n",
    "\n",
    "    portman(natalie(d)) ⇒ 'twone'\n",
    "    \n",
    "Within `natalie`, we repeatedly add words to a `result` list until we have used up all the unique `words` from the dictionary. On each iteration we either add a `new_word` (thus decreasing the size of the remaining `words`), or we re-use a `repeated_word`, choosing one that will bridge to a word that we have not used yet. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def natalie(d: Dictionary) -> list:\n",
    "    \"Return a list of words that cover the dictionary.\"\n",
    "    words  = set(d.uniq)   # all the words we need to cover\n",
    "    result = [words.pop()] # a list of overlapping words\n",
    "    firsts = Counter(word[0] for word in words) # Count of first letters of words\n",
    "    while words:\n",
    "        prev = result[-1]\n",
    "        word = (new_word(d, prev, words) or repeated_word(d, prev, firsts))\n",
    "        result.append(word)\n",
    "        if word in words:\n",
    "            words.remove(word)\n",
    "            B = word[0]\n",
    "            firsts[B] -= 1\n",
    "            if not firsts[B]: del firsts[B]\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Selecting the Next Word\n",
    "\n",
    "Selecting a `new_word` is easy: consider the suffixes of the previous word, longest suffix first, and if that suffix is a prefix of an unused word, then take it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def new_word(d: Dictionary,  prev: str, words: set) -> str or None:\n",
    "    \"Find an overlapping word to follow the previous word (or None).\"\n",
    "    for suf in suffixes(prev):\n",
    "        if suf in d.pre:\n",
    "            for word in d.pre[suf]:\n",
    "                if word in words:\n",
    "                    return word"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now suppose we reach a situation where the previous word was `'one'`, and the only remaining unused word is `'two'`. Since there is no overlap, `new_word` will fail, but we can find the shortest previously-used word that will `bridge` from the `'e'` at the end of `'one'` to the `'t'` at the start of `'two'`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "@lru_cache(1000)\n",
    "def bridge(d, A, B) -> str:\n",
    "    \"Find a word that bridges A to B: it starts with A and ends with B.\"\n",
    "    return shortest(word for word in d.pre[A] if word.endswith(B))\n",
    "\n",
    "def shortest(items): return min(items, key=len, default=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'eat'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bridge(D, 'e', 't')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But in general, there will be several unusued words that we might bridge to; we will greedily choose the shortest bridge to any of the unused words. That sounds expensive when there are thousands of unused words, so we will summarize them with a counter, `firsts`, that gives for each letter the number of unused words that start with that letter (so, if the unused words are `{'two', 'three', 'four'}`, then `firsts` will be `{'t': 2, 'f': 1}`).\n",
    "\n",
    "Furthermore, it might be that *no* word can bridge directly to an unused word. In that case we can take two steps, first bridging from `A` to an intermediate letter `L`, and then bridging from `L` to a letter `B` that starts some unused word. The function `repeated_word` handles all these cases:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def repeated_word(d: Dictionary,  prev: str, firsts: Counter) -> str:\n",
    "    \"Find a previously-used word that will bridge to one of the letters in firsts.\"\n",
    "    A = prev[-1]\n",
    "    word = shortest(bridge(d, A, B) for B in firsts if bridge(d, A, B))\n",
    "    if word:\n",
    "        return word\n",
    "    else:\n",
    "        candidates = [[bridge(d, A, L), bridge(d, L, B)] \n",
    "                      for L in alphabet for B in firsts\n",
    "                      if A != L != B and bridge(d, A, L) and bridge(d, L, B)]\n",
    "        return min(candidates, key=lambda seq: sum(map(len, seq)))[0]\n",
    "\n",
    "alphabet = 'abcdefghijklmnopqrstuvwxyz'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example, suppose the previous word is `'one'`, and the only remaining unused word is `'quit'`. There is no word that bridges from `'e'` to `'q'`. So we will have to get there in two steps. Here's the first step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'elhi'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "repeated_word(D, 'one', {'q': 1})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And here's the second:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'iraq'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "repeated_word(D, 'elhi', {'q': 1})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A Solution\n",
    "\n",
    "We're ready to solve the problem!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 23.2 s, sys: 50.7 ms, total: 23.2 s\n",
      "Wall time: 23.3 s\n"
     ]
    }
   ],
   "source": [
    "%%time \n",
    "L = natalie(D)\n",
    "S = portman(L)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(101796, 64389, 575150)"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(L), len(D.uniq), len(S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we see the start of the list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['hyperactivity',\n",
       " 'typewriting',\n",
       " 'tingling',\n",
       " 'lingeries',\n",
       " 'escarping',\n",
       " 'carpings',\n",
       " 'stropped',\n",
       " 'peddles',\n",
       " 'lesbians',\n",
       " 'answers',\n",
       " 'ersatzes',\n",
       " 'zestiest',\n",
       " 'establisher',\n",
       " 'sherlocks',\n",
       " 'locksmiths',\n",
       " 'swankily',\n",
       " 'lyricizing',\n",
       " 'zingers',\n",
       " 'erstwhile',\n",
       " 'whiled']"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "L[:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the start of the string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'hyperactivitypewritinglingeriescarpingstroppeddlesbianswersatzestiestablisherlocksmithswankilyricizingerstwhileditorializingedifiestashedableachesapeakednessayistsunamicabilitieschewalsocializedshopliftsarsaparillasersheiksignalmanacsimonizedelweissestinescapablymphomassacrestingstowagesturalliescudosserscoundrellyinglycosideswipingrassessorshipmateshipwaysidestepsonshipshapelessnessentiallylstreptococcuspidalliersnorterservilitieschewinglessonedictallyhoedownstairsicknessesamesospheredityranniseismologyratessellatediouslyesteryearshotspursierrantrystsarinasmuchnessayeditorialistlesslyerbassoonistsarismsectarianismelteriescargotsardomsilhouettinglesseesaweddingsulfurizedematadorsallyingrowthsplurgesturingtailskidskinsmendeleviumbrageoushereditarilynxesculentsunamissilerysipelasticizeducationshorelinesmandragoraphobiaxialitympanumskullsleighingelessonslaughtsktskingedgewaysinewspeakshepherdingingivaerologistsaritzassagaislesionstagehandsomesthesisesquicentenniallymphocytestifyingestantalizationiumsketchingsubfamiliescapistsetsessilencesariannulightingstungstensilesiamesestinassimilableakishkestrelsewhereforestedhorseshoestringsideswipestilencesspitsawtoothpickstretchablenchedarwinistsimmeshinglersophsuperlativelysianticipatoryxescarpmentsktskedgesturescuestashingleditorializestsarevnasturtiumsavagedlyceesquiringboltsaristshamrockshenaniganswerabilitypographerselfedscoopsfullerythematologicalumnymphsilkweedinessentialleliciteddyingscreechymicsouvenirstargazersalutessellationspeedwaysquintingeingeniousnessayersequesterselysiumteenthronementsalivateddiesesquicentennialslumberserksadistsubclassessablearingdovestingsaguarosebaywoodsiestashesitatediousnessayingsluicewaywardlyristsumpsychrotherapiestradiologistshowingspansyllabicspikeletspoonerismswazilandownershipsidetrackingshipshottingliestablishmentsolarismsturdynamistickinessayscarrierspearmenianschlussreineducabilitypifyinguinalterablyricizeducativehiclessoningrainingloriouslynessesquipedalianestheticsextsoddynamismse'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "S[:2000]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to see the whole string, I'll write it to the file [natalie.txt](natalie.txt)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "575150"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "open('natalie.txt', 'w').write(S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Next Steps\n",
    "\n",
    "Each time I run this, I get a slightly different result (there are no `random` calls, but each Python re-start gets a random hash seed, which results in a different iteration order over dicts and sets).  I had originally planned to add some randomness and take the best of *k* trials (like I did in my [TSP](TSP.ipynb) notebook), but all the trials I have seen so far fall within a narrow range of 575,000 to 581,000 letters, so I think it is not worth the effort for what would probably be a 1% improvement at best. My string is 6% shorter than Murphy's solution with 611,820 letters. \n",
    "\n",
    "I'll stop here (but you should feel free to do some experimentation of your own). Some ideas:\n",
    "\n",
    "- One weakness of my approach is that it can get stuck. With `W = {'one', 'two'}`, if my algorithm chooses  `'one'` as the starting word, it will fail. You could fix that by allowing new words to be added to the start of the list (hint: use a `dequeue`) as well as the end.\n",
    "- Following my [TSP](TSP.ipynb) notebook, an alternative to maintaining a single list and adding the maximum-overlap word is to maintain multiple lists, and on each iteration merge the lists with maximum overlap.\n",
    "- With the 108,709 it is always possible to bridge from any letter to any other letter in at most two steps. But for smaller dictionaries, that might not be the case. You could consider that.\n",
    "- To minimize the length of S, we can do three things: get better overlap between the unique words, use fewer/shorter bridging words, or get better overlap of the bridging words. Can you think of strategies to achieve any of these?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Tests\n",
    "\n",
    "This gives some examples of how the functions are used, and some assurance that they are doing the right thing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pass'"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def test(D):\n",
    "    W = {'on', 'one', 'two', 'won'}\n",
    "    S =  'twone'\n",
    "    L = ['two', 'won', 'on', 'one']\n",
    "    assert portman(L) == S\n",
    "    assert all(w in S for w in W)\n",
    "    assert set(L) == W\n",
    "    \n",
    "    assert prefixes('word') == ['w', 'wo', 'wor', 'word']\n",
    "    assert suffixes('word') == ['word', 'ord', 'rd', 'd']\n",
    "    assert subwords({'hello', 'world', 'he', 'hell', 'el', 'or'}) == (\n",
    "                   {'el', 'he', 'hell', 'or'})\n",
    "    assert multimap([(1, 10), (2, 20), (3, 30), (2, 22), (3, 33)]) == (\n",
    "                   {1: [10], 2: [20, 22], 3: [30, 33]})\n",
    "    \n",
    "    assert 'portmanteau' in D.words\n",
    "    assert 'port'        in D.words\n",
    "    assert 'port'        not in D.uniq\n",
    "    assert set(D.pre['hello']) == {'hello', 'helloed', 'helloes', 'helloing', 'hellos'}\n",
    "    \n",
    "    assert bridge(D, 'a', 'z') == 'abuzz'\n",
    "    assert bridge(D, 'a', 't') == 'at'\n",
    "    assert bridge(D, 'e', 't') == 'eat'\n",
    "    assert bridge(D, 'f', 'd') == 'fad'\n",
    "    \n",
    "    assert portman(['two', 'won', 'on', 'one']) == 'twone'\n",
    "    assert portman(['eskimo', 'kimono', 'monolith']) == 'eskimonolith'\n",
    "\n",
    "    return 'pass'\n",
    "    \n",
    "test(D)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
